package com.walkline.music;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;
import javax.microedition.media.Control;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;

import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.media.MediaKeyListener;
import net.rim.device.api.media.control.AudioPathControl;
import net.rim.device.api.system.Application;

import com.walkline.util.Function;

public class MusicPlayer
{
	Player _player;
	VolumeControl _volumeControl;
	AudioPathControl _audioPathControl;
	PlayerListener _listener;
	int _currentVolume = 80;

	public MusicPlayer() {Application.getApplication().addKeyListener(new myMediaKeyListener());}

	public void setPlayerListener(PlayerListener listener) {_listener = listener;}

	public void play(String url)
	{
		stop();
		//closeMp3();

		try {
			ConnectionDescriptor connd = new ConnectionFactory().getConnection(url);
			HttpConnection conn = (HttpConnection) connd.getConnection();

			conn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);

			int resCode = conn.getResponseCode();

			switch (resCode)
			{
				case HttpConnection.HTTP_OK: 
				{
					InputStream inputStream = conn.openInputStream();

					_player = Manager.createPlayer(inputStream, "audio/mpeg");
					if (_player != null)
					{
						_player.addPlayerListener(_listener);
						_player.realize();
						_player.prefetch();
						_volumeControl = (VolumeControl) _player.getControl("VolumeControl");
						_volumeControl.setLevel(_currentVolume);

						/*
						Control[] controls = _player.getControls();
						for (int i=0; i<controls.length; i++)
						{
							if (controls[i] instanceof AudioPathControl)
							{
								_audioPathControl = (AudioPathControl) controls[i];
								if (_audioPathControl.canSwitchToPath(AudioPathControl.AUDIO_PATH_HEADSET))
								{
									_audioPathControl.setAudioPath(AudioPathControl.AUDIO_PATH_HEADSET);
								} else if (_audioPathControl.canSwitchToPath(AudioPathControl.AUDIO_PATH_HANDSFREE)) {
									_audioPathControl.setAudioPath(AudioPathControl.AUDIO_PATH_HANDSFREE);
								}
							}
						}
						*/
						_player.start();
					}

					break;
				}
			}
		} catch (IOException e) {Function.errorDialog(e.toString());}
		  catch (MediaException e) {Function.errorDialog(e.toString());}
	}

	public void stop()
	{
		if (_player != null)
		{
			if (_player.getState() != Player.CLOSED)
			{
				try {
					_player.stop();
				} catch (MediaException e) {Function.errorDialog(e.toString());}
			}			
		}
	}

	public void close() {if (_player != null) {_player.close();}}

	public void pause()
	{
		if (_player != null)
		{
			if (_player.getState() == Player.STARTED)
			{
				try {
					_player.stop();
				} catch (MediaException e) {}
			} else if (_player.getState() == Player.PREFETCHED) {
				try {
					_player.start();
				} catch (MediaException e) {}
			}		
		}
	}

	public String getStatus()
	{
		int status = _player.getState();
		String result = "";

		switch (status)
		{
			case Player.CLOSED:
				result = "Closed";
				break;
			case Player.PREFETCHED:
				result = "Prefetched";
				break;
			case Player.REALIZED:
				result = "Realized";
				break;
			case Player.STARTED:
				result = "Started";
				break;
			case Player.UNREALIZED:
				result = "Unrealized";
				break;
		}

		return result;
	}

	public long getMediaTime()
	{
		long time = _player.getMediaTime();

		if (time == Player.TIME_UNKNOWN) {time = 0;}

		return time;
	}

	public int getMediaTimePercent()
	{
		long currentTime = _player.getMediaTime();
		long durationTime = _player.getDuration() / 1000;

		return ((int) (currentTime / durationTime)) * 100;
	}

	public long getDurationTime()
	{
		long time = _player.getDuration();

		if (time == Player.TIME_UNKNOWN) {time = 0;}

		return time;
	}

	class myMediaKeyListener extends MediaKeyListener
	{
		public boolean mediaAction(int action, int source, Object context)
		{
			if (_player != null)
			{
				if (_player.getState() == Player.STARTED)
				{
					if (_volumeControl != null)
					{
						switch (action)
						{
							case MEDIA_ACTION_VOLUME_UP:
								_volumeControl.setLevel(_volumeControl.getLevel() + 5);
								_currentVolume = _volumeControl.getLevel();
								Function.infoDialog("音量: " + _currentVolume + "%");
								return true;
							case MEDIA_ACTION_VOLUME_DOWN:
								_volumeControl.setLevel(_volumeControl.getLevel() - 5);
								_currentVolume = _volumeControl.getLevel();
								Function.infoDialog("音量: " + _currentVolume + "%");
								return true;
							case MEDIA_ACTION_PLAYPAUSE_TOGGLE:
								try {
									_player.stop();
								} catch (MediaException e) {}
								return true;
						}
					}
				} else if (_player.getState() == Player.PREFETCHED) {
					if (_volumeControl != null)
					{
						switch (action)
						{
							case MEDIA_ACTION_PLAYPAUSE_TOGGLE:
								try {
									_player.start();
								} catch (MediaException e) {}
								return true;
						}
					}
				}
			}

			return false;
		}
	}
}